//
const fs = require("fs");
//
const addRoute = function(fnCollection){
    const router = require("express").Router();
    for (const key in fnCollection) {
        let routeName,
            getRegx = /GET\s+?/,
            postRegx = /POST\s+?/;
        if (fnCollection.hasOwnProperty(key)) {
            if(getRegx.test(key)){
                routeName = key.replace(getRegx,"");
                router.get(routeName,fnCollection[key]);
            }
            if(postRegx.test(key)){
                routeName = key.replace(postRegx,"");
                router.post(routeName,fnCollection[key]);
            }
        }
    }
    return router;
}
//
const setAppRouter = function(app){
    /* 请求设置??? */
    app.all("*", ( req, res, next )=>{
        res.header("Access-Control-Allow-Origin","*");
        res.header( 'Access-Control-Allow-Headers', 'X-Requested-With,Content-type' );
        res.header( 'Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS' );
        res.header( 'Content-Type', 'application/json;charset=utf-8');
        next();
    });
    /* 路由设置??? */
    let js_files = fs.readdirSync(`${__dirname}/modules`).filter(f=>f.endsWith(".js"));
    /*  */
    js_files.forEach(js_file=>{
        const fc = require(`${__dirname}/modules/${js_file}`);
        //
        app.use(fc.path, addRoute(fc));
    });
    //错误处理---???
    app.use(( err, req, res, next )=>{
        console.log(err);
        console.log(process.env.NODE_ENV);
        /* let result = 
            process.env.NODE_ENV === "development"
            ?{
                error:{
                    message:err.message,
                    name:err.name,
                    stack:err.stack
                }
            }
            :{}; */
        let result = {
            error:{
                message:err.message,
                name:err.name,
                stack:err.stack
            }
        };
        console.log(result);
        res.status(err.status || 500);
        res.json(result);
    });
};
//
exports.setAppRouter = setAppRouter;